//
// Created by root on 17-3-10.
//

#include <string.h>
#include <iostream>
#include <public.h>
#include "sand.h"
#include "json.h"
#include "public.h"
#include "hikv_api.h"
#include "ctrl_utils.h"

HikvisionAPI::HikvisionAPI() {

}

HikvisionAPI::~HikvisionAPI() {

}

int HikvisionAPI::hikv_capture_picture(uint32_t channel, std::string &dev_picture) {
    CtrlCfg::Yaml_Config_ST config_st = pctrl_cfg->get_config_st();
    CtrlCfg::Dev_Config_Map config_map =  pctrl_cfg->get_dev_config_map();

    char *log_path = config_st.sdklog_dir;
    uint32_t log_level = config_st.sdklog_level;
    bool log_autodel = config_st.sdklog_autodel;
    
    char *ip;
    uint32_t port;
    char *username;
    char *password;
    for (auto it=config_map.begin(); it!=config_map.end(); ++it) {
        ip = it->second.dev_ip;
        port = it->second.dev_port;
        username = it->second.dev_username;
        password = it->second.dev_password;
    }

    uint32_t pic_quality = config_st.snapshot_picture_quality;
    uint32_t pic_size = config_st.snapshot_picture_size;

    std::string create_path;
    std::string pic_path(config_st.snapshot_picture_path);
    if (pic_path.back() != '/') {
        create_path = pic_path  + "/" + sand::format(sand::now(), "yyyy-mm-dd");
    } else {
        create_path = pic_path + sand::format(sand::now(), "yyyy-mm-dd");
    }

    mkpath(create_path, 0755);

    std::string file_name = "dvr" + std::to_string(channel) + "-" +
                            sand::format(sand::now(), "yyyy-mm-dd-HH:MM:SS.MS") + ".jpeg";
    std::string pic_file = create_path + "/" + file_name;
    char *picture_file = strdup(pic_file.c_str());

    NET_DVR_Init();
    NET_DVR_SetLogToFile(log_level, log_path, log_autodel);

    NET_DVR_DEVICEINFO_V30 struDeviceInfo = {0};
    LONG user_id = NET_DVR_Login_V30(ip, port, username, password, &struDeviceInfo);
    if (user_id < 0) {
        //std::cout<<"net_dvr login error, errinfo: "<<NET_DVR_GetLastError()<<std::endl;
        NET_DVR_Cleanup();
        return HPR_ERROR;
    }

    NET_DVR_JPEGPARA strPicPara = {0};
    strPicPara.wPicQuality = pic_quality;
    strPicPara.wPicSize = pic_size;
    int iRet;
    iRet = NET_DVR_CaptureJPEGPicture(user_id, channel, &strPicPara, strdup(picture_file));//struDeviceInfo.byStartChan
    if (!iRet) {
        //std::cout<<"net_dvr capture picture error, errinfo: "<<NET_DVR_GetLastError<<std::endl;
        return HPR_ERROR;
    }
    dev_picture = pic_file;

    NET_DVR_Logout_V30(user_id);
    NET_DVR_Cleanup();

    return HPR_OK;
}
